#!/usr/bin/perl


use 5.010;
use warnings;
use strict;



my @arr=([],[]);
my $coord;
my $c1;
my $c2;
my $c3;
my $c4;
my $bool=0;

sub map1
{
  for (my $i = 0; $i <11; $i++)
     {
	  for (my $j = 0; $j <11; $j++)
	  {	    
	      $arr[$i][$j]=' . ';
	    
	  }
      }
}
sub printmap
{	
  say '';
  for (my $i = 0; $i <11; $i++)
     {
	if ($i == 0) {
	    print " .  0  1  2  3  4  5  6  7  8  9 ";
	}
	else {
	  for (my $j = 0; $j <11; $j++)
	  {
	    if ($j == 0) {
	      print " ",(($i-1))," ";
	    }
	    else { 	    
	      print "$arr[$i][$j]";
	    }
	  }
	}
	say '';
      }
      say '';      
}
sub check
{
	      my $a3 = $c3+1;
	      my $a4 = $c4+1;
	      for(my $a1 =$c1-1;$a1 < $a3;$a1++)
	      {
		for(my $a2 = $c2-1;$a2 < $a4;$a2++)	
		{
		  if($arr[$a1+1][$a2+1] eq '[X]')
		  {
		    $bool=1;last;
		  }		  
		}		
	      }
}
sub getcoord
{
    for (my $i = 0; $i < 11; $i++)
     {  
	print "Enter coordinate or command: ";
	$coord = <STDIN>;
	($c1,$c2,$c3,$c4)=split(//,$coord,4);
	 
	given($coord){
	  when ("exit\n") {last;}
	  when ("print\n"){&printmap;$i--;}
	  when ("clear\n"){&map1;$i=0;}
	  when ((/^[0-9]{4}\n$/) && ($c1 == $c3 || $c2 == $c4)) 
	  {	 
	      my $len1;
	      my $len2;
	      $len1= (($c4-$c2+1));	  
	      $len2= (($c3-$c1+1));
	      if ($len1>4 || $len2>4){
		say 'Ship is too long!';
		continue;
	      }
	      &check;
	      if($bool == 1)
		{
		  say 'Your ships crossed or too close!';
		  $bool = 0;
		  continue;
		}
	      if($c1 == $c3)
	      {	
		  for(my $k=0;$k < $len1;$k++){
		    $arr[$c1+1][$c2+$k+1]='[X]';      
		  }
	      }
	      else{		  
		  for(my $g=0;$g < $len2;$g++){
		    $arr[$c1+1+$g][$c2+1]='[X]';
		  }
	      }
	      say 'Well done.';
	      
	   }
	  
	  default{print "Wrong coordinate: $coord";$i--;}
	}
      }
  say '';    
  say "Final field!";
  &printmap;
}
    


&map1;
say "___________________Battleship v2.1___________________";
say '';
say "Enter coordinates of 10 ships";
say "(in format \"abcd\" ,where \"ab\" start coordinate, \"cd\" end coordinate)";
say "For exit enter____________________________________________exit";
say "For printing the field with ships enter___________________print";
say "For clear the field enter_________________________________clear";
say '';
&printmap;
&getcoord;